package com.ytjj.qmyx.supplychain.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.kuaidi100.sdk.request.SupplyChainBrandRequest;
import com.kuaidi100.sdk.response.ProductCategoryResp;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.constants.RedisConstants;
import com.ytjj.qmyx.supplychain.common.utils.HttpClientUtil;
import com.ytjj.qmyx.supplychain.common.utils.RedisService;
import com.ytjj.qmyx.supplychain.mapper.*;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
public class SupplyChainBrandService {

    @Resource
    private SupplyChainBrandMapper supplyChainBrandMapper;
    @Resource
    private ProductCategoryService productCategoryService;
    @Resource
    private ProductCategoryMapper productCategoryMapper;
    @Resource
    private BankerProductMapper bankerProductMapper;
    @Resource
    private RedisService redisService;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private NotifyUrlInfoMapper notifyUrlInfoMapper;

    public CommonPage list(SupplyChainBrandRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<YxSupplyChainBrand> yxSupplyChainBrands = supplyChainBrandMapper.selectAllByCondition(request);

        String redisProductCategoryVal = redisService.get(RedisConstants.SUPPLY_PRODUCT_CATEGORY);
        List<ProductCategoryResp> productCategoryRespList = new ArrayList<>();
        if (com.alibaba.excel.util.StringUtils.isEmpty(redisProductCategoryVal)) {
            productCategoryRespList = productCategoryMapper.selectProductCategory();
            redisService.set(RedisConstants.SUPPLY_PRODUCT_CATEGORY, JSONObject.toJSONString(productCategoryRespList));
            redisService.expire(RedisConstants.SUPPLY_PRODUCT_CATEGORY, 60 * 60);
        }else {
            productCategoryRespList = JSONObject.parseArray(redisProductCategoryVal, ProductCategoryResp.class);
        }

        List<ProductCategoryResp> finalProductCategoryRespList = productCategoryRespList;
        yxSupplyChainBrands.stream().forEach(item ->{
            //获取分类id
            String categoryListStr = item.getRelevenceCategory();
            if (StringUtils.isBlank(categoryListStr)) {
                return;
            }
            String[] region = categoryListStr.split(",");
//            Optional<String> flag = Stream.of(region).filter(x -> x.equals(item.getId())).findFirst();
            //通过所得的ids获取到分类对象集合
            List<ProductCategoryResp> list = finalProductCategoryRespList.stream().filter(productCategoryResp -> Stream.of(region).filter(x -> x.equals(productCategoryResp.getId().toString())).findFirst().isPresent()).collect(Collectors.toList());
            //分类集合进行排序(三级放二级,二级放一级里)
            List<ProductCategoryResp> productCategoryResp = productCategoryService.getProductCategoryResps(list);
            //定义好一二三级分类
            List<String> categoryList = new ArrayList<>();//分类集合
            productCategoryResp.forEach(category -> {
                List<ProductCategoryResp> childProductCategory = category.getChildProductCategory();
                if (!CollectionUtils.isEmpty(childProductCategory)) {
                    childProductCategory.forEach(twoCategory -> {
                        List<ProductCategoryResp> bottomProductCategory = twoCategory.getChildProductCategory();
                        if (!CollectionUtils.isEmpty(bottomProductCategory)) {
                            bottomProductCategory.forEach(bottomCategory -> {
                                String categoryTitles = "";
                                categoryTitles = category.getTitle() + " - " + twoCategory.getTitle() + " - " + bottomCategory.getTitle();
                                categoryList.add(categoryTitles);
                            });
                        } else {
                            String categoryTitles = "";
                            categoryTitles = category.getTitle() + " - " + twoCategory.getTitle();
                            categoryList.add(categoryTitles);
                        }
                    });
                } else {
                    String categoryTitles = category.getTitle();
                    categoryList.add(categoryTitles);
                }
            });
            item.setRelevenceCategoryName(categoryList);
        });
        return CommonPage.restPage(yxSupplyChainBrands);
    }

    public CommonResult all(String chineseName) {
        Example example = new Example(YxSupplyChainBrand.class);
        example.createCriteria().andNotEqualTo("brandStatus",0);
        example.setOrderByClause("id desc");
        return CommonResult.success(supplyChainBrandMapper.selectByExample(example));
    }

    public Integer addAndUpdate(YxSupplyChainBrand yxSupplyChainBrand) {
        Integer i = 0;
        yxSupplyChainBrand.setUpdateTime(new Date());

        if (StringUtils.isEmpty(yxSupplyChainBrand.getCountry())) {
            yxSupplyChainBrand.setCountry("中国");
        }
        if (null != yxSupplyChainBrand.getId()) {
//            if (null != yxSupplyChainBrand.getBrandStatus() && (yxSupplyChainBrand.getBrandStatus() == 0 || yxSupplyChainBrand.getBrandStatus() == 2)){
//                Example example = new Example(YxProduct.class);
//                example.createCriteria().andEqualTo("brandId",yxSupplyChainBrand.getId());
//                int i1 = productMapper.selectCountByExample(example);
//                if (i1 > 0){
//                    return i;
//                }
//            }
            YxSupplyChainBrand yxSupplyChainBrand1 = supplyChainBrandMapper.selectByPrimaryKey(yxSupplyChainBrand.getId());
            yxSupplyChainBrand.setOldName(yxSupplyChainBrand1.getChineseName());
            if (yxSupplyChainBrand.getBrandStatus() == 2) {
                i = supplyChainBrandMapper.deleteByPrimaryKey(yxSupplyChainBrand.getId());
                productMapper.updateBrandByBrandId(yxSupplyChainBrand.getId());
                bankerProductMapper.updateBrandByBrandId(yxSupplyChainBrand.getId());
            }else {
                i = supplyChainBrandMapper.updateByPrimaryKeySelective(yxSupplyChainBrand);
//                if (yxSupplyChainBrand.getBrandStatus() == 0){
//                    productMapper.updateBrandByBrandId(yxSupplyChainBrand.getId());
//                    bankerProductMapper.updateBrandByBrandId(yxSupplyChainBrand.getId());
//                }
            }
        } else {
            i = supplyChainBrandMapper.insertSelective(yxSupplyChainBrand);
        }
        //新增或修改渠道品牌
        Example example2 = new Example(YxNotifyUrlInfo.class);
        example2.createCriteria().andEqualTo("type", 3);
        List<YxNotifyUrlInfo> notifyUrlInfos = notifyUrlInfoMapper.selectByExample(example2);
        log.info("======供应链调用新增或修改渠道品牌======notifyUrlInfos={}",notifyUrlInfos);

        if (!CollectionUtils.isEmpty(notifyUrlInfos)) {
            SupplyChainBrandRequest request = SupplyChainBrandRequest.builder()
                    .id(yxSupplyChainBrand.getId())
                    .chineseName(yxSupplyChainBrand.getChineseName())
                    .brandLogo(yxSupplyChainBrand.getBrandLogo())
                    .brandBanner(yxSupplyChainBrand.getBrandBanner())
                    .brandDescr(yxSupplyChainBrand.getBrandDescr())
                    .country(yxSupplyChainBrand.getCountry())
                    .oldChineseName(null != yxSupplyChainBrand.getId() ? yxSupplyChainBrand.getOldName() : null)
                    .isShow(yxSupplyChainBrand.getBrandStatus() != 1 ? 0 : 1)
                    .brandStatus(yxSupplyChainBrand.getBrandStatus())
                    .build();
            notifyUrlInfos.stream().forEach(item -> {
                log.info("======供应链调用新增或修改渠道品牌====参数==={},{}", request, item.getUrl());
                String s = HttpClientUtil.doPostJson(item.getUrl(), JSONObject.toJSONString(request));
                log.info("======供应链调用新增或修改渠道品牌====返回==={}", s);
            });
        }
        return i;
    }

    public List<YxSupplyChainBrand> selectByIds(SupplyChainBrandRequest request) {
        List<YxSupplyChainBrand> yxSupplyChainBrands = supplyChainBrandMapper.selectAllByCondition(request);
        return yxSupplyChainBrands;
    }
}
